import D2Ext

from .CImage import CImage
from .CLabel import CLabel
from .Constants import *


class CButton(CImage):

    def __init__(self, parent=None):
        super(CButton, self).__init__(parent)
        self.frame_up = 0
        self.frame_down = 1
        self.text = CLabel("", self)
        self.text_x = self.text.x
        self.text_y = self.text.y
        self.text_position = BUTTON_TEXT_CENTER

    def set_button_frame(self, up, down):
        self.frame_up = up
        self.frame_down = down
        self.set_frame(up)

    def set_position(self, x, y):
        super(CButton, self).set_position(x, y)

        if self.text:
            t_width = self.text.text_width()
            self.text_x = (self.width - t_width) / 2
            t_height = 12
            self.text_y = (self.height - t_height) / 2 + t_height
            self.text.set_position(self.text_x, self.text_y)

    def set_text(self, text):
        self.text.set_text(text)

        t_width = self.text.text_width()
        self.text_x = (self.width - t_width) / 2
        t_height = 12
        self.text_y = (self.height - t_height) / 2 + t_height
        self.text.set_position(self.text_x, self.text_y)
        #
        # D2Ext.LogMsg("self.x=%s,self.y=%s,self.width=%s,self.height=%s" % (self.x, self.y, self.width, self.height))
        # D2Ext.LogMsg("t_x=%s,t_y=%s" % (t_x, t_y))

    def draw(self):
        if self.being_pressed:
            self.set_frame(self.frame_down)
            self.text.set_position(self.text_x - 1, self.text_y + 1)
        else:
            self.set_frame(self.frame_up)
            self.text.set_position(self.text_x, self.text_y)

        if self.image_file:
            D2Ext.Image_Draw(self.image_file, self.dx, self.dy + self.height, self.opacity)

    def show(self):
        super(CButton, self).show()
        self.text.show()

    def hide(self):
        super(CButton, self).hide()
        self.text.hide()
